package org.command.main;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class PhoneLocationService {
    // 方法用于查询手机号码归属地
    public String queryLocationByPhoneNumber(String phoneNumber) throws IOException {
        String xmlResponse = null;
        try {
            String userID = " ";

            // 构建请求URL
            String apiUrl = "http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo";
            String requestUrl = apiUrl + "?mobileCode=" + phoneNumber + "&userID=" + userID;

            // 创建URL对象
            URL url = new URL(requestUrl);

            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法为GET
            connection.setRequestMethod("GET");

            // 获取响应代码
            int responseCode = connection.getResponseCode();
            if (responseCode == 200) {
                // 读取响应数据
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String line;
                StringBuilder response = new StringBuilder();

                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();

                // 处理响应数据
                xmlResponse = response.toString();
                System.out.println("API响应:");
            } else {
                System.out.println("HTTP请求失败，响应代码：" + responseCode);
            }

            connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return xmlResponse;
    }
}
